from Config.myConstant import *
from Config.myConfig import *
from DataPrepare.tickFactors.factorBase import factorBase
from DataAccess.TickDataProcess import TickDataProcess
import pandas as pd
import numpy as np
import math
class dailyPriceChange(factorBase):
    #----------------------------------------------------------------------
    def __init__(self):
        #super(buySellVolumeRatio,self).__init__()
        super().__init__()
        self.factor='dailyPriceChange'
        pass
    #----------------------------------------------------------------------
    def getFactorFromLocalFile(self,code,date):
        mydata=super().getFromLocalFile(code,date,'midPriceChange')
        return mydata
        pass
    def updateFactor(self,code,date,data=pd.DataFrame()):
        exists=super().checkLocalFile(code,date,self.factor)
        if exists==True:
            logger.info(f'No need to compute! {self.factor} of {code} in {date} exists!')
            pass
        if data.shape[0]==0:
             #data=TickDataProcess().getDataByDateFromLocalFile(code,date)
             data=TickDataProcess().getTickShotDataFromInfluxdbServer(code,date)
        result=self.computerFactor(code,date,data)
        super().updateFactor(code,date,self.factor,result)
    def computerFactor(self,code,date,mydata):
        result=pd.DataFrame()
        if mydata.shape[0]!=0:
            result=mydata[['midPrice','tick']].copy()
            result['midPrice'].fillna(method='ffill',inplace=True)

            openPrice = mydata['lastPrice'].iloc[0]
            if (openPrice == 0):
                openPrice = mydata['midPrice'].iloc[0]

            result['midPriceIncrease']=(result['midPrice']-result['midPrice'].shift(1))/result['midPrice'].shift(1)
            #前推前3mMidPrice的波动率
            result['midStd60']=result['midPriceIncrease'].rolling(60,min_periods=1).std()*math.sqrt(14400/3)
            result['midStd60'].fillna(method='ffill',inplace=True)
            select=result['midStd60'].isna()==True
            result.loc[select,'midStd60']=0

        else:
            logger.error(f'There no data of {code} in {date} to computer factor!') 
        return result
    

########################################################################
